namespace DotNetNuke.Security.Authentication
{
    using DotNetNuke.Common;
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Users;
    using DotNetNuke.Security;
    using DotNetNuke.Services.Log.EventLog;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Web;
    using System.Web.Security;

    public class AuthenticationController
    {
        private PortalSettings _portalSettings;
        private string mProcessLog = "";
        private string mProviderTypeName = "";

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public AuthenticationController()
        {
            Configuration _config = Configuration.GetConfig();
            this._portalSettings = PortalController.GetCurrentPortalSettings();
            this.mProviderTypeName = _config.ProviderTypeName;
        }

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public void AuthenticationLogoff()
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            string authCookies = "authentication_" + _portalSettings.PortalId.ToString();
            FormsAuthentication.SignOut();
            if (GetStatus(_portalSettings.PortalId) == AuthenticationStatus.WinLogon)
            {
                SetStatus(_portalSettings.PortalId, AuthenticationStatus.WinLogoff);
            }
            if (PortalSecurity.IsInRoles(_portalSettings.AdministratorRoleId.ToString()) & (HttpContext.Current.Request.Cookies["_Tab_Admin_Content" + _portalSettings.PortalId.ToString()] != null))
            {
                HttpContext.Current.Response.Cookies["_Tab_Admin_Content" + _portalSettings.PortalId.ToString()].Value = null;
                HttpContext.Current.Response.Cookies["_Tab_Admin_Content" + _portalSettings.PortalId.ToString()].Path = "/";
                HttpContext.Current.Response.Cookies["_Tab_Admin_Content" + _portalSettings.PortalId.ToString()].Expires = DateTime.Now.AddYears(-30);
            }
            HttpContext.Current.Response.Cookies["portalaliasid"].Value = null;
            HttpContext.Current.Response.Cookies["portalaliasid"].Path = "/";
            HttpContext.Current.Response.Cookies["portalaliasid"].Expires = DateTime.Now.AddYears(-30);
            HttpContext.Current.Response.Cookies["portalroles"].Value = null;
            HttpContext.Current.Response.Cookies["portalroles"].Path = "/";
            HttpContext.Current.Response.Cookies["portalroles"].Expires = DateTime.Now.AddYears(-30);
            if (_portalSettings.HomeTabId != -1)
            {
                HttpContext.Current.Response.Redirect(Globals.NavigateURL(_portalSettings.HomeTabId), true);
            }
            else if (_portalSettings.ActiveTab.IsAdminTab)
            {
                HttpContext.Current.Response.Redirect("~/Default.aspx", true);
            }
            else
            {
                HttpContext.Current.Response.Redirect(Globals.NavigateURL(), true);
            }
        }

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public void AuthenticationLogon()
        {
            Configuration _config = Configuration.GetConfig();
            DotNetNuke.Security.Authentication.UserController objAuthUserController = new DotNetNuke.Security.Authentication.UserController();
            DotNetNuke.Entities.Users.UserController objDNNUserController = new DotNetNuke.Entities.Users.UserController();
            string authCookies = "authentication_" + this._portalSettings.PortalId.ToString();
            string LoggedOnUserName = HttpContext.Current.Request.ServerVariables["LOGON_USER"];
            if (LoggedOnUserName.Length > 0)
            {
                int intUserId=0;
                DotNetNuke.Security.Authentication.UserInfo objAuthUser;
                DotNetNuke.Entities.Users.UserInfo objDNNUser = objDNNUserController.GetUserByUsername(this._portalSettings.PortalId, LoggedOnUserName);
                if (objDNNUser != null)
                {
                    intUserId = objDNNUser.UserID;
                    if (_config.SynchronizeRole)
                    {
                        objAuthUser = objAuthUserController.GetUser(LoggedOnUserName);
                        if (objAuthUser.GUID.Length != 0)
                        {
                            objAuthUser.UserID = intUserId;
                            DotNetNuke.Security.Authentication.UserController.AddUserRoles(this._portalSettings.PortalId, objAuthUser);
                        }
                    }
                }
                else
                {
                    objAuthUser = objAuthUserController.GetUser(LoggedOnUserName);
                    objDNNUser = objAuthUser;
                    if (objAuthUser != null)
                    {
                        intUserId = objAuthUserController.AddDNNUser(objAuthUser);
                        SetStatus(this._portalSettings.PortalId, AuthenticationStatus.WinLogon);
                    }
                }
                if (intUserId > 0)
                {
                    FormsAuthentication.SetAuthCookie(Convert.ToString(LoggedOnUserName), true);
                    SetStatus(this._portalSettings.PortalId, AuthenticationStatus.WinLogon);
                    string ipAddress = "";
                    if (HttpContext.Current.Request.UserHostAddress != null)
                    {
                        ipAddress = HttpContext.Current.Request.UserHostAddress;
                    }
                    EventLogController objEventLog = new EventLogController();
                    LogInfo objEventLogInfo = new LogInfo();
                    objEventLogInfo.AddProperty("IP", ipAddress);
                    objEventLogInfo.LogPortalID = this._portalSettings.PortalId;
                    objEventLogInfo.LogPortalName = this._portalSettings.PortalName;
                    objEventLogInfo.LogUserID = intUserId;
                    objEventLogInfo.LogUserName = LoggedOnUserName;
                    objEventLogInfo.AddProperty("WindowsAuthentication", "True");
                    objEventLogInfo.LogTypeKey = "LOGIN_SUCCESS";
                    objEventLog.AddLog(objEventLogInfo);
                }
            }
            string strURL = Globals.NavigateURL(this._portalSettings.ActiveTab.TabID, "", new string[] { "logon=windows" });
            HttpContext.Current.Response.Redirect(strURL, true);
        }

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public Array AuthenticationTypes()
        {
            return AuthenticationProvider.Instance(this.mProviderTypeName).GetAuthenticationTypes();
        }

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public DotNetNuke.Entities.Users.UserInfo GetDNNUser(int PortalID, string LoggedOnUserName)
        {
            DotNetNuke.Entities.Users.UserController objDNNUserController = new DotNetNuke.Entities.Users.UserController();
            DotNetNuke.Entities.Users.UserInfo objUser = objDNNUserController.GetUserByUsername(Null.NullInteger, LoggedOnUserName);
            if (objUser != null)
            {
                if (objDNNUserController.GetUserByUsername(PortalID, LoggedOnUserName) == null)
                {
                    objUser.PortalID = PortalID;
                    objUser.UserID = objDNNUserController.AddUser(objUser, true);
                }
                return objUser;
            }
            return null;
        }

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public static AuthenticationStatus GetStatus(int PortalID)
        {
            AuthenticationStatus GetStatus=AuthenticationStatus.Undefined;
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            string authCookies = "authentication.status." + PortalID.ToString();
            try
            {
                if (HttpContext.Current.Request.Cookies[authCookies] != null)
                {
                    FormsAuthenticationTicket AuthenticationTicket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[authCookies].Value);
                    return (AuthenticationStatus) Conversions.ToInteger(Enum.Parse(typeof(AuthenticationStatus), AuthenticationTicket.UserData));
                }
                GetStatus = AuthenticationStatus.Undefined;
            }
            catch (Exception exception1)
            {
                
                Exception ex = exception1;
                
            }
            return GetStatus;
        }

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public string NetworkStatus()
        {
            return AuthenticationProvider.Instance(this.mProviderTypeName).GetNetworkStatus();
        }

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public DotNetNuke.Security.Authentication.UserInfo ProcessFormAuthentication(string LoggedOnUserName, string LoggedOnPassword)
        {
            Configuration _config = Configuration.GetConfig();
            DotNetNuke.Security.Authentication.UserController objAuthUserController = new DotNetNuke.Security.Authentication.UserController();
            DotNetNuke.Entities.Users.UserController objUsers = new DotNetNuke.Entities.Users.UserController();
            if (_config.WindowsAuthentication)
            {
                return objAuthUserController.GetUser(LoggedOnUserName, LoggedOnPassword);
            }
            return null;
        }

        /// -------------------------------------------------------------------
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [tamttt]	08/01/2004	Created
        /// </history>
        /// -------------------------------------------------------------------
        public static void SetStatus(int PortalID, AuthenticationStatus Status)
        {
            string authCookies = "authentication.status." + PortalID.ToString();
            HttpRequest Request = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;
            FormsAuthenticationTicket AuthenticationTicket = new FormsAuthenticationTicket(1, authCookies, DateTime.Now, DateTime.Now.AddHours(1.0), false, Status.ToString());
            string strAuthentication = FormsAuthentication.Encrypt(AuthenticationTicket);
            if (Request.Cookies[authCookies] != null)
            {
                Request.Cookies[authCookies].Value = null;
                Request.Cookies[authCookies].Path = "/";
                Request.Cookies[authCookies].Expires = DateTime.Now.AddYears(-1);
            }
            Response.Cookies[authCookies].Value = strAuthentication;
            Response.Cookies[authCookies].Path = "/";
            Response.Cookies[authCookies].Expires = DateTime.Now.AddHours(1.0);
        }
    }
}

